/**
 * @author hanzc (hanzhichen@baijia.com)
 * @date 2021-01-20
 * fineBi经分概览看板part1: 收入看板
 */
import React, {useState} from 'react';
import {useMount, useSetState} from 'ahooks';
import {Row, Col, Card, Input, Progress, Typography} from 'antd';
import {
    querySelectOptions,
    queryValues,
    queryDetail,
    download
} from '~/service/refundReport';
import {numberHandle} from '~/utils/number';
import {PROGRESS_COLOR} from '~/page/FineBi/utils/color';
import CommonSearchBar from '../../../common/CommonSearchBar';
import DetailCard from '../../../common/DetailCard';
import DetailModal from '../../../common/DetailModal';
import Loading from '../../../common/Loading';
import {convertSearcherParams} from '../../../utils/convert';
import {searchFormPart1} from '../../config';
import DetailCardTableV2 from '../../../common/DetailCardTableV2';
import HorizonTable from '../../../common/HorizonTable';
import RefundSourcePieChart from './RefundSourcePieChart';
import RefundCenterBarChart from './RefundCenterBarChart';
import MonthRefundBarChart from './MonthRefundBarChart';


const {Title} = Typography;
const {TextArea} = Input;

const DashboardIdPre = 'refundKanbanOnePart';
const SELECT_UNIT_ID = 'selectUnit_12';
const PRECISION = 2;
const initialValues = {};

const DashboardCfg1 = [
    {
        dashBoardName: 'refundKanbanOnePart_partOne',
        dashBoardId: 'refundKanbanOnePart_partOne'
    },
    {
        dashBoardName: 'refundKanbanOnePart_partOne_Two',
        dashBoardId: 'refundKanbanOnePart_partOne_Two'
    },
    {
        dashBoardName: 'refundKanbanOnePart_partTwo',
        dashBoardId: 'refundKanbanOnePart_partTwo'
    },
    {
        dashBoardName: 'refundKanbanOnePart_partThree',
        dashBoardId: 'refundKanbanOnePart_partThree'
    },
    {
        dashBoardName: 'refundKanbanOnePart_partFour',
        dashBoardId: 'refundKanbanOnePart_partFour'
    }
];

/** 经分概览看板part1: 收入看板 */
const RefundOnTimeDashBoard = () => {
    const [loading, setLoading] = useState(false);
    const [loading1, setLoading1] = useState(false);
    const [loading2, setLoading2] = useState(false);
    const [result, setResult] = useSetState({});
    // searchform
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    // drilling
    const [drilingList, setDrilingList] = useState([]);
    const [drilingLevel, setDrilingLevel] = useState(null);
    // detail
    const [detailData, setDetailData] = useState({});
    const [detailModalVisible, setDetailModalVisible] = useState(false);

    // 返回结果是这样的格式.
    const {
        refundKanbanOnePart_partOne: dayRefundData = {},
        refundKanbanOnePart_partOne_Two: monthRefundData = {},
        refundKanbanOnePart_partTwo: refundCardsData = {},
        refundKanbanOnePart_partThree: refundSourceData = {},
        refundKanbanOnePart_partFour: refundCenterData = {}
    } = result;
    const {
        refundKanbanOnePart_partOne_card_1: card1Data = {},
        refundKanbanOnePart_partOne_excel_1: card1Value = {},
        refundKanbanOnePart_partOne_text_1: discriptionText = {}
    } = dayRefundData;

    const {
        refundKanbanOnePart_partOne_Two_card_1: card2Data = {},
        refundKanbanOnePart_partOne_Two_excel_1: card2Value = {},
        refundKanbanOnePart_partOne_Two_bar_1: monthRefundBarChartData = {}
    } = monthRefundData;
    const {
        refundKanbanOnePart_partTwo_card_1: simpleCard1 = {},
        refundKanbanOnePart_partTwo_card_2: simpleCard2 = {},
        refundKanbanOnePart_partTwo_card_3: simpleCard3 = {}
    } = refundCardsData;
    const {
        refundKanbanOnePart_partThree_pie_1: refundSourcePieChartData = {}
    } = refundSourceData;
    const {
        refundKanbanOnePart_partFour_composite: refundCenterBarchartData = {},
        refundKanbanOnePart_partFour_excel_1: refundCenterExcelData = {}
    } = refundCenterData;

    // cardTable 处理2个
    const nameIdx = '学部';
    const valueIdx = '退款金额';
    const title2 = numberHandle(
        card2Data?.cardValues?.[0]?.value ?? 0,
        PRECISION
    );
    const moneyList2 = card2Value?.value?.map(item => {
        const {[nameIdx]: name, [valueIdx]: value} = item;
        return {name, value: numberHandle(value, PRECISION)};
    });
    const title1 = numberHandle(
        card1Data?.cardValues?.[0]?.value ?? 0,
        PRECISION
    );
    const moneyList1 = card1Value?.value?.map(item => {
        const {[nameIdx]: name, [valueIdx]: value} = item;
        return {name, value: numberHandle(value, PRECISION)};
    });

    // 退费中心表格数据处理
    const {
        columnList = [],
        value: tableDataSource = []
    } = refundCenterExcelData;
    const newColumnList = columnList
        ?.map(item => {
            if (item.name === '业绩归属人中心') {
                return {order: 0, key: item.id, dataIndex: item.name};
            }
            if (item.name === '退费金额') {
                return {order: 1, key: item.id, dataIndex: item.name};
            }
            return {
                order: Number.MAX_SAFE_INTEGER,
                key: item.id,
                dataIndex: item.name
            };
        })
        .sort((a, b) => a?.order - b?.order);
    const newTableDataSource = tableDataSource?.map(item => {
        const {退费金额 = 0} = item;
        return {...item, 退费金额: numberHandle(退费金额, PRECISION)};
    });
    // 处理返回数据结束

    /** 查询方法 */
    const getData = (params = {}) => {
        const {
            dashBoardList = [],
            dimensionAndValues = [],
            loadingFn = setLoading,
            ...restParams
        } = params;
        loadingFn(true);
        Promise.all(
            dashBoardList.map((oneDashboard = {}) => {
                const {dashBoardId = ''} = oneDashboard;
                const newDimensionAndValues = dimensionAndValues.map(
                    ({dimensionId: dimId = '', ...restDAV} = {}) => ({
                        dimensionId: `${dashBoardId}_${dimId}`,
                        ...restDAV
                    })
                );
                return queryValues({
                    dashBoardList: [oneDashboard],
                    dimensionAndValues: newDimensionAndValues,
                    ...restParams
                }).then(res => {
                    const {data = {}} = res;
                    setResult({...data});
                });
            })
        ).finally(() => {
            loadingFn(false);
        });
    };

    /** 点击搜索按钮 */
    const handleSearch = params => {
        setSearchFormValues(params);
        setDrilingLevel(null);
        setDrilingList([]);
        const queryParams = {
            dashBoardList: DashboardCfg1,
            drilingList: [],
            dimensionAndValues: convertSearcherParams(params)
        };
        getData(queryParams);
    };
    const handleReset = () => {
        setSearchFormValues(initialValues);
        setDrilingLevel(null);
        setDrilingList([]);
        const queryParams = {
            dashBoardList: DashboardCfg1,
            drilingList: [],
            dimensionAndValues: convertSearcherParams(initialValues)
        };
        getData(queryParams);
    };
    // detail
    // 函数柯里化, 提前记录unit参数
    const handleDetail = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        setDetailModalVisible(true);
        const newDimensionAndValues = convertSearcherParams(
            searchFormValues
        ).map(({dimensionId: dimId = '', ...restDAV} = {}) => ({
            dimensionId: `${dashBoardId}_${dimId}`,
            ...restDAV
        }));
        const params = {
            dimensionAndValues: newDimensionAndValues || [],
            unitId,
            unitName,
            drilingList
        };
        queryDetail(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };
    const handleDownload = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        const newDimensionAndValues = convertSearcherParams(
            searchFormValues
        ).map(({dimensionId: dimId = '', ...restDAV} = {}) => ({
            dimensionId: `${dashBoardId}_${dimId}`,
            ...restDAV
        }));
        const params = {
            dimensionAndValues: newDimensionAndValues || [],
            unitId,
            unitName,
            drilingList
        };
        const excelName = unitName ? unitName : null;
        download(params, excelName);
    };
    const handleBack = ({unitId = ''} = {}, loadingFn) => async params => {
        if (unitId === 'refundKanbanOnePart_partThree_pie_1') {
            loadingFn = setLoading1;
        }
        else if (unitId === 'refundKanbanOnePart_partFour_composite') {
            loadingFn = setLoading2;
        }
        // 所有下钻取消
        setDrilingList([]);
        try {
            const queryParams = {
                dashBoardList: DashboardCfg1,
                drilingList: [],
                dimensionAndValues: convertSearcherParams(searchFormValues)
            };

            await getData({...queryParams, loadingFn});
            // 返回搜索数据接口调用成功后level - 1
            setDrilingLevel({unitId, level: 0});
        } catch {}
    };
    // drilling, 下钻, 会重新加载模块
    const handleDrilling = (chartUnit = {}, loadingFn) => async params => {
        if (chartUnit?.unitId === 'refundKanbanOnePart_partThree_pie_1') {
            loadingFn = setLoading1;
        }
        else if (chartUnit?.unitId === 'refundKanbanOnePart_partFour_composite') {
            loadingFn = setLoading2;
        }
        const {info} = params;
        const {unitId = '', unitName = '', config = {}} = chartUnit;
        const {dimensionList = []} = config;
        const [firstDimension] = dimensionList;
        const {dimensionId = '', dimensionName = ''} = firstDimension || {};
        const driling = {
            unitId,
            unitName,
            value: info?.name,
            dimensionId,
            dimensionName
        };
        setDrilingList([driling]);
        try {
            const queryParams = {
                dashBoardList: DashboardCfg1,
                drilingList: [driling],
                dimensionAndValues: convertSearcherParams(searchFormValues)
            };
            await getData({...queryParams, loadingFn});
            // 搜索接口调用成功后level + 1, 现在是0就是没下钻, 1就是有下钻, 多级下钻也是1.
            setDrilingLevel({unitId, level: 1});
        } catch {}
    };
    // 请求单个表单配置项
    const handleFetchOptions = ({
        key,
        searchKey,
        pager,
        dependItemKey,
        dependItemValue,
        isGetingMore,
        options: curOptions,
        fieldsValue
    }) => {
        let permissions = searchFormPart1.map(item => ({
            dimensionId: `${DashboardIdPre}_${item.key}`,
            dimensionName: item.key,
            filterItems: Array.isArray(fieldsValue[item.key])
                ? fieldsValue[item.key]
                : fieldsValue[item.key] == null
                    ? []
                    : [fieldsValue[item.key]]
        }));

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: `${DashboardIdPre}_${key}`,
            dimensionName: key,
            searchKey,
            permissions,
            unitId: SELECT_UNIT_ID
        };

        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    // mount
    useMount(() => {
        const queryParams = {
            dashBoardList: DashboardCfg1,
            drilingList: [],
            dimensionAndValues: convertSearcherParams(initialValues)
        };
        getData(queryParams);
    }, []);

    return (
        <div>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    noCache
                    config={searchFormPart1}
                    selectOptions={selectOptions}
                    initialValues={initialValues}
                    onOk={handleSearch}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    loading={loading}
                />
            </Card>
            <Card>
                <div style={{marginBottom: 8}}>
                    <Loading loading={loading}>
                        <TextArea
                            value={discriptionText?.textContent}
                            readOnly
                            bordered={false}
                            className="refund-text-area"
                            style={{height: 108}}
                        />
                    </Loading>
                </div>
                <Row style={{flex: '1'}}>
                    <Col span={12}>
                        <DetailCard
                            title={card2Value?.unitName ?? ''}
                            onDownload={handleDownload(
                                card2Value,
                                'refundKanbanOnePart_partOne_Two'
                            )}
                            onDetail={handleDetail(
                                card2Value,
                                'refundKanbanOnePart_partOne_Two'
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <DetailCardTableV2
                                    dataSource={moneyList2}
                                    title={title2}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={12}>
                        <DetailCard
                            title={card1Value?.unitName ?? ''}
                            onDownload={handleDownload(
                                card1Value,
                                'refundKanbanOnePart_partOne'
                            )}
                            onDetail={handleDetail(
                                card1Value,
                                'refundKanbanOnePart_partOne_Two'
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <DetailCardTableV2
                                    dataSource={moneyList1}
                                    title={title1}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <DetailCard
                            title={monthRefundBarChartData?.unitName ?? ''}
                            onDownload={handleDownload(
                                monthRefundBarChartData,
                                'refundKanbanOnePart_partOne_Two'
                            )}
                            onDetail={handleDetail(
                                monthRefundBarChartData,
                                'refundKanbanOnePart_partOne_Two'
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <MonthRefundBarChart
                                    dataSource={monthRefundBarChartData}
                                    id="MonthRefundBarChart"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
                <Row>
                    <Col span={8}>
                        <DetailCard
                            title={simpleCard1?.unitName ?? ''}
                            onDownload={handleDownload(
                                simpleCard1,
                                'refundKanbanOnePart_partTwo'
                            )}
                            onDetail={handleDetail(
                                simpleCard1,
                                'refundKanbanOnePart_partTwo'
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <Row justify="center">
                                    <Progress
                                        type="dashboard"
                                        percent={
                                            (simpleCard1?.cardValues?.[0]?.value ??
                                                0) * 100
                                        }
                                        format={percent => `${percent.toFixed(2)}%`}
                                        strokeColor={PROGRESS_COLOR}
                                    />
                                </Row>
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={8}>
                        <DetailCard
                            title={simpleCard2?.unitName ?? ''}
                            onDownload={handleDownload(
                                simpleCard2,
                                'refundKanbanOnePart_partTwo'
                            )}
                            onDetail={handleDetail(
                                simpleCard2,
                                'refundKanbanOnePart_partTwo'
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <Row justify="center">
                                    <Progress
                                        type="dashboard"
                                        percent={
                                            (simpleCard2?.cardValues?.[0]?.value ??
                                                0) * 100
                                        }
                                        format={percent => `${percent.toFixed(2)}%`}
                                        strokeColor={PROGRESS_COLOR}
                                    />
                                </Row>
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={8}>
                        <DetailCard
                            title={simpleCard3?.unitName ?? ''}
                            onDownload={handleDownload(
                                simpleCard3,
                                'refundKanbanOnePart_partTwo'
                            )}
                            onDetail={handleDetail(
                                simpleCard3,
                                'refundKanbanOnePart_partTwo'
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <Row justify="center">
                                    <Progress
                                        type="dashboard"
                                        percent={
                                            (simpleCard3?.cardValues?.[0]?.value ??
                                                0) * 100
                                        }
                                        format={percent => `${percent.toFixed(2)}%`}
                                        strokeColor={PROGRESS_COLOR}
                                    />
                                </Row>
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <DetailCard
                            title={refundSourcePieChartData?.unitName ?? ''}
                            onDownload={handleDownload(
                                refundSourcePieChartData,
                                'refundKanbanOnePart_partThree'
                            )}
                            onDetail={handleDetail(
                                refundSourcePieChartData,
                                'refundKanbanOnePart_partThree'
                            )}
                            onBack={handleBack(refundSourcePieChartData)}
                            showBack={
                                drilingLevel &&
                                drilingLevel?.unitId ===
                                    refundSourcePieChartData?.unitId &&
                                drilingLevel?.level > 0
                            }
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading1 || loading}>
                                <RefundSourcePieChart
                                    dataSource={refundSourcePieChartData}
                                    id="RefundSourcePieChart"
                                    onDrilling={handleDrilling(
                                        refundSourcePieChartData
                                    )}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={12}>
                        <DetailCard
                            title={refundCenterBarchartData?.unitName ?? ''}
                            onDownload={handleDownload(
                                refundCenterBarchartData,
                                'refundKanbanOnePart_partFour'
                            )}
                            onDetail={handleDetail(
                                refundCenterBarchartData,
                                'refundKanbanOnePart_partFour'
                            )}
                            onBack={handleBack(refundCenterBarchartData)}
                            showBack={
                                drilingLevel &&
                                drilingLevel?.unitId ===
                                    refundCenterBarchartData?.unitId &&
                                drilingLevel?.level > 0
                            }
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading2 || loading}>
                                <RefundCenterBarChart
                                    dataSource={refundCenterBarchartData}
                                    id="RefundCenterBarChart"
                                    onDrilling={handleDrilling(
                                        refundCenterBarchartData
                                    )}
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
                {/* <Row>
                    <Col span={24}>
                        <Card style={{height: '100%'}}>
                            <HorizonTable
                                columns={newColumnList}
                                dataSource={newTableDataSource}
                            />
                        </Card>
                    </Col>
                </Row> */}
            </Card>
            <DetailModal
                data={detailData}
                detailModalVisible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
            />
        </div>
    );
};

export default RefundOnTimeDashBoard;
